<template>
  <div>
    <el-switch
      v-model="draggableState"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button v-if="draggableState" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="getCheckedKeys">批量删除</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedkey"
      :expand-on-click-node="false"
      :draggable="draggableState"
      :allow-drop="allowDrop"
      @node-drag-end="handleDrop"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            update
          </el-button>
          <el-button
            v-if="node.childNodes == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如:组件，工具js，第三方插件jsjson文件，图片文件等等)
//例如:import《组件名称》from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      draggableState: false,
      title: "",
      expandedkey: [],
      dialogVisible: false,
      data: [],
      category: {
        catId: null,
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        icon: "",
        productUnit: "",
      },

      defaultProps: {
        children: "children",
        label: "name",
      },
      updateNodes: [],
      pCid: [],
      //最大等级
      maxLevel: 1,
    };
  },
  //计算属性 类型于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //查询分类
    getMenusTree() {
      this.$http({
        url: this.$http.adornUrl("/gulimallproduce/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        this.data = data.data;
      });
    },
    //批量删除
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys());
      this.$http({
        url: this.$http.adornUrl("/gulimallproduce/category/delete"),
        method: "post",
        data: this.$http.adornData(this.$refs.tree.getCheckedKeys(), false),
      }).then(({ data }) => {
        console.log(data);
        location.reload;
      });
      this.getMenusTree();
    },
    //添加窗口
    append(data) {
      this.title = "添加";
      this.dialogVisible = true;
      this.category.catId = null;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      console.log("append", data);
    },
    //修改
    update(data) {
      this.title = "修改";
      this.category = data;
      this.dialogVisible = true;
      console.log(data);
    },

    //保存
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/gulimallproduce/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        console.log(data);

        this.$message({
          message: "恭喜你，这是一条成功消息",
          type: "success",
        });

        //刷新订单
        this.getMenusTree
        // 展开节点
        this.expandedkey=this.pCid
        this.updateNodes=[],
        this.maxLevel=1;
      });
    },

    //删除
    remove(node, data) {
      console.log("remove:", node, data);
      this.$confirm(`是否删除[${data.name}]`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/gulimallproduce/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {});

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getMenusTree();
          this.expandedkey = [node.parent.data.catId];
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加事件
    addCategory() {
      console.log(this.category);

      var url = "/gulimallproduce/category/save";
      if (this.category.catId) {
        url = "/gulimallproduce/category/update";
      }

      this.$http({
        url: this.$http.adornUrl(url),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        console.log(data);
        this.dialogVisible = false;
        this.getMenusTree();
        this.expandedkey = [this.category.parentCid];
      });
    },

    //移动事件
    allowDrop(draggingNode, dropNode, type) {
      //1、被拖动的当前节点以及所在的父节点总层数不能大于3
      console.log(draggingNode, dropNode, type);

      this.maxLevel = 1;
      //计算节点
      this.countNodeLevel(draggingNode);

      //当前正在拖动的节点+父节点所在的深度不大于3即可
      //let deep=this.maxLevel+draggingNode.level
      console.log(this.maxLevel, "被拖住的深度+++++++++++++++");

      if (type == "inner") {
        return this.maxLevel + dropNode.level <= 3;
      } else {
        return this.maxLevel + dropNode.parent.level <= 3;
      }
    },

    //计算被拖拽的层级
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length != 0) {
        for (var i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[0].level > this.maxLevel) {
            this.maxLevel = node.childNodes[0].level;
          }
          this.countNodeLevel(node.childNodes[0]);
        }
      }
    },

    //拖拽结束修改数据
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("操作结束: ", draggingNode, dropNode, dropType);

      //当前节点的最新父id
      let pid = 0;
      let siblings = null;

      if (dropType != "none") {
        if (dropType == "before" || dropType == "after") {
          pid =
            dropNode.data.parentCid == undefined ? 0 : dropNode.data.parentCid;
          siblings = dropNode.childNodes;
          console.log(pid, siblings);
        } else {
          pid = dropNode.data.catId;
          siblings = dropNode.childNodes;
        }
        console.log(`最新父ID${pid}`);
        this.pCid.push(pid);

        //当前节点的最新顺序
        for (var i = 0; i < siblings.length; i++) {
          if (siblings[i].data.catId == draggingNode.data.catId) {
            //如果遍历的是当前正在拖拽的节点
            let catLevel = draggingNode.level;

            if (siblings[i].level != draggingNode.level) {
              //当前节点的层级发生变化
              catLevel = siblings[i].level;
              //修改他子节点的层级
              this.updateChildNodeLevel(siblings[i]);
            }

            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i,
              patentCid: pid,
              catLevel: catLevel,
            });
          } else {
            this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
          }
        }
        //最后拖拽的层级
        console.log("结果为：", this.updateNodes);
      }
    },

    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
  },

  //生命周期 -创建完成*（可以访问当前this示例)
  created() {
    this.getMenusTree();
  },
  // //生命周期 -挂载完成(可以访问dom元素)
  // mounted() {},
  // beforeCreate() {}, //生命周期–创建之前
  // beforeMount() {}, //生命周期–挂载之前
  // beforeUpdate() {}, //生命周期–更新之前
  // updated() {}, //生命周期–更新之后
  // beforeDestroy() {}, //生命周期–销毁之前
  // destroyed() {}, //生命周期–销毁完成
  // activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>